//
//  MapVC.m
//  Tan_TestGDMap
//
//  Created by 亲哥哥 on 2018/4/29.
//  Copyright © 2018年 yam. All rights reserved.
//

#import "MapVC.h"
#import <MAMapKit/MAMapKit.h>
#import <AMapLocationKit/AMapLocationKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import "POIAnnotation.h"
#import "ReGeocodeAnnotation.h"
#import "GeocodeAnnotation.h"

@interface MapVC ()<MAMapViewDelegate, AMapLocationManagerDelegate, AMapSearchDelegate, UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UILabel *addressLbl;
@property (nonatomic, strong) UITextField *searchField;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArr;

@property (nonatomic, strong) MAMapView *mapView;      //地图控件
@property (nonatomic, strong) AMapLocationManager *locationManager; //定位管理器
@property (nonatomic, strong) AMapSearchAPI *search;   //poi搜索api
@property (nonatomic, strong) ReGeocodeAnnotation *annotation;

@end

@implementation MapVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self initOtherControls];
    
    CGSize size = [UIScreen mainScreen].bounds.size;
    self.mapView = [[MAMapView alloc] initWithFrame:CGRectMake(10, 110, size.width-20, size.height-120)];
    self.mapView.delegate = self;
    self.mapView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    self.mapView.zoomLevel = 16;
    self.mapView.showsUserLocation = YES;  //显示用户位置
    [self.mapView setUserTrackingMode:MAUserTrackingModeFollow animated:YES]; //设置用户追踪模式
    [self.view addSubview:self.mapView];
    
    self.locationManager = [[AMapLocationManager alloc] init];
//    self.locationManager.distanceFilter = 100; //设定定位的最小更新距离，匹配mapView.zoomLevel = 16
    self.locationManager.delegate = self;
    [self.locationManager setLocatingWithReGeocode:YES];
    [self.locationManager startUpdatingLocation];
    
    //poi搜索
    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
}

#pragma mark - MAMapViewDelegate
- (void)mapView:(MAMapView *)mapView regionDidChangeAnimated:(BOOL)animated{
    NSLog(@"缩放级：%d", (int)self.mapView.zoomLevel);
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    static NSString *poiIdentifier = @"poiIdentifier";
    MAPinAnnotationView *poiAnnotationView = (MAPinAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:poiIdentifier];
    if (poiAnnotationView == nil)
    {
        poiAnnotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:poiIdentifier];
    }
    
    poiAnnotationView.canShowCallout = YES;
    poiAnnotationView.animatesDrop = YES;
    //        poiAnnotationView.rightCalloutAccessoryView = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
    
    return poiAnnotationView;
}

#pragma mark - AMapLocationManagerDelegate
/**
 *  @brief 连续定位回调函数.注意：如果实现了本方法，则定位信息不会通过amapLocationManager:didUpdateLocation:方法回调。
 *  @param manager 定位 AMapLocationManager 类。
 *  @param location 定位结果。
 *  @param reGeocode 逆地理信息。
 */
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location reGeocode:(AMapLocationReGeocode *)reGeocode{
    
    NSLog(@"....获取定位信息。。。%d", self.mapView.zoomLevel);
    NSLog(@"%@", reGeocode.formattedAddress);
    NSLog(@"%@， %@， %@", reGeocode.province, reGeocode.city, reGeocode.country);
    
    self.addressLbl.text = reGeocode.formattedAddress?reGeocode.formattedAddress:@"";
}

#pragma mark - AMapSearchDelegate
/* POI 搜索回调. */
- (void)onPOISearchDone:(AMapPOISearchBaseRequest *)request response:(AMapPOISearchResponse *)response
{
    [self.mapView removeAnnotations:self.mapView.annotations];
    
    if (response.pois.count == 0)
    {
        return;
    }
    
    NSMutableArray *poiAnnotations = [NSMutableArray arrayWithCapacity:response.pois.count];
    
    [response.pois enumerateObjectsUsingBlock:^(AMapPOI *obj, NSUInteger idx, BOOL *stop) {
        
        [poiAnnotations addObject:[[POIAnnotation alloc] initWithPOI:obj]];
        
    }];
    
    /* 将结果以annotation的形式加载到地图上. */
    [self.mapView addAnnotations:poiAnnotations];
    
    /* 如果只有一个结果，设置其为中心点. */
    if (poiAnnotations.count == 1)
    {
        [self.mapView setCenterCoordinate:[poiAnnotations[0] coordinate]];
    }
    /* 如果有多个结果, 设置地图使所有的annotation都可见. */
    else
    {
        [self.mapView showAnnotations:poiAnnotations animated:NO];
    }
    
    [self.dataArr removeAllObjects];
    [self.dataArr addObjectsFromArray:response.pois];
    self.tableView.hidden = NO;
    [self.view bringSubviewToFront:self.tableView];
    [self.tableView reloadData];
}

//地址编码回调
- (void)onGeocodeSearchDone:(AMapGeocodeSearchRequest *)request response:(AMapGeocodeSearchResponse *)response
{
    [self.mapView removeAnnotations:self.mapView.annotations];
    if (response.geocodes.count == 0)
    {
        return;
    }
    
    NSMutableArray *annotations = [NSMutableArray array];
    
    [response.geocodes enumerateObjectsUsingBlock:^(AMapGeocode *obj, NSUInteger idx, BOOL *stop) {
        GeocodeAnnotation *geocodeAnnotation = [[GeocodeAnnotation alloc] initWithGeocode:obj];
        
        [annotations addObject:geocodeAnnotation];
    }];
    
    if (annotations.count == 1)
    {
        [self.mapView setCenterCoordinate:[annotations[0] coordinate] animated:YES];
    }
    
    [self.mapView addAnnotations:annotations];
}

/* 逆地理编码回调. */
- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response
{
    [self.mapView removeAnnotations:self.mapView.annotations];
    if (response.regeocode != nil)
    {
        CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(request.location.latitude, request.location.longitude);
        ReGeocodeAnnotation *reGeocodeAnnotation = [[ReGeocodeAnnotation alloc] initWithCoordinate:coordinate
                                                                                         reGeocode:response.regeocode];
        
        [self.mapView addAnnotation:reGeocodeAnnotation];
        [self.mapView selectAnnotation:reGeocodeAnnotation animated:YES];
    }
    else /* from drag search, update address */
    {
        [self.annotation setAMapReGeocode:response.regeocode];
        [self.mapView selectAnnotation:self.annotation animated:YES];
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    
    if (cell == nil){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
        cell.textLabel.font = [UIFont systemFontOfSize:12];
    }
    
    AMapPOI *poi = self.dataArr[indexPath.row];
    cell.textLabel.text = [NSString stringWithFormat:@"%@%@%@%@", poi.province, poi.city, poi.district, poi.address];
    
    return cell;
}
#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    AMapPOI *poi = self.dataArr[indexPath.row];
    self.tableView.hidden = YES;
    
    //1、地址编码查询
//    AMapGeocodeSearchRequest *request = [AMapGeocodeSearchRequest new];
//    request.address = poi.address;
//    request.city = poi.city;
//    [self.search AMapGeocodeSearch:request];
    
//    //地址编码查询接口
//    - (void)AMapGeocodeSearch:(AMapGeocodeSearchRequest *)request;
//    //逆地址编码查询接口
//    - (void)AMapReGoecodeSearch:(AMapReGeocodeSearchRequest *)request;
    
    //2、逆地址编码查询
    AMapReGeocodeSearchRequest *reRequest = [AMapReGeocodeSearchRequest new];
    reRequest.location = poi.location;
    [self.search AMapReGoecodeSearch:reRequest];
}

- (void)initOtherControls{
    
    self.view.backgroundColor = [UIColor whiteColor];
    CGSize size = [UIScreen mainScreen].bounds.size;
    self.dataArr = [NSMutableArray new];
    
    UIButton *backBtn = [[UIButton alloc] initWithFrame:CGRectMake(10, 30, 60, 30)];
    backBtn.backgroundColor = [UIColor grayColor];
    [backBtn setTitle:@"返回" forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backLastPage) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:backBtn];
    
    //展示当前选择的地址
    self.addressLbl = [[UILabel alloc] initWithFrame:CGRectMake(80, 30, size.width-90, 30)];
    self.addressLbl.font = [UIFont systemFontOfSize:12];
    self.addressLbl.numberOfLines = 0;
    [self.view addSubview:self.addressLbl];
    
    //搜索
    self.searchField = [[UITextField alloc] initWithFrame:CGRectMake(10, 70, size.width - 90, 30)];
    self.searchField.placeholder = @"请输入搜索关键字";
    self.searchField.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10, 30)];
    self.searchField.leftViewMode = UITextFieldViewModeAlways;
    self.searchField.layer.borderColor = [UIColor grayColor].CGColor;
    self.searchField.layer.borderWidth = 1;
    self.searchField.layer.masksToBounds = YES;
    self.searchField.layer.cornerRadius = 4;
    [self.view addSubview:self.searchField];
    
    UIButton *searchBtn = [[UIButton alloc] initWithFrame:CGRectMake(size.width-70, 70, 60, 30)];
    searchBtn.backgroundColor = [UIColor grayColor];
    [searchBtn setTitle:@"搜索" forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(startSearch) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:searchBtn];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 200, size.width, size.height-200)];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:self.tableView];
    self.tableView.hidden = YES;
}
- (void)backLastPage{
    [self dismissViewControllerAnimated:YES completion:nil];
}

//开始搜搜
- (void)startSearch{
    
    self.tableView.hidden = YES;
    [self.searchField resignFirstResponder];
    NSString *keyword = self.searchField.text;
    
    if (keyword.length < 1) return;
    
    AMapPOIKeywordsSearchRequest *request = [[AMapPOIKeywordsSearchRequest alloc] init];
    request.keywords = keyword;
    //    request.keywords            = @"北京大学";
    //    request.city                = @"北京";
    //    request.types               = @"高等院校";
    //    request.requireExtension    = YES;
    //
    //    /*  搜索SDK 3.2.0 中新增加的功能，只搜索本城市的POI。*/
    //    request.cityLimit           = YES;
    request.requireSubPOIs      = YES;
    
    [self.search AMapPOIKeywordsSearch:request];
}

- (void)dealloc{
    
    NSLog(@"...%@。。。控制器被销毁...", [self class]);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
